package com.hmall.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.dto.Address;
import com.hmall.common.dto.Item;
import com.hmall.common.web.ExampleClient;

import com.hmall.common.web.UserClient;
import com.hmall.item.util.RegexUtils;
import com.hmall.order.common.constant;
import com.hmall.order.dto.OrderDTO;
import com.hmall.order.exception.BaseException;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.service.IOrderDetail;
import com.hmall.order.service.IOrderLogistics;
import com.hmall.order.service.IOrderService;
import com.hmall.order.util.SnowflakeIdWorker;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    public OrderMapper orderMapper;

    @Autowired
    public ExampleClient exampleClient;

    @Autowired
    public IOrderDetail iOrderDetail;

    @Autowired
    public UserClient userClient;

    @Autowired
    IOrderLogistics iOrderLogistics;

    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public String creationOrderFrom(OrderDTO order) {

        //雪花算法生成id
        String snowFlakeId = SnowflakeIdWorker.getSnowflakeId();
        //商品微服务提供FeignClient，实现根据id查询商品的接口
        //根据itemId查询商品信息
        //基于商品价格、购买数量计算商品总价：totalFee
        //封装Order对象，初识status为未支付
        Integer integer=0;
        if (order.getNum()!=null){
             integer = Integer.valueOf(order.getNum());
        }

        Order order1 = new Order();
        order1.setStatus(1);
        order1.setCreateTime(new Date());
        order1.setId(Long.valueOf(snowFlakeId));
        // 设置过期时间为当前时间加上30分钟
        order1.setCloseTime(new Date(System.currentTimeMillis() + 30 * 60 * 1000));
        order1.setPaymentType(Integer.valueOf(order.getPaymentType()));
        //需要获取用户id







        order1.setUserId(2l);
        //此处需要加判断
        Item item = exampleClient.selectById(Long.valueOf(order.itemId));
        order1.setTotalFee(item.getPrice()*integer);
        //将Order写入数据库tb_order表中
        int insert = orderMapper.insert(order1);
        String RedisKey= "2"+UUID.randomUUID();
        redisTemplate.opsForValue().set(RedisKey,order1);
        redisTemplate.expire(RedisKey,30, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(RedisKey+ constant.KEY_USER,order1);
        //将商品信息、orderId信息封装为OrderDetail对象，写入tb_order_detail表
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(order1.getId());
        orderDetail.setCreateTime(new Date(System.currentTimeMillis()));
        orderDetail.setImage(item.getImage());
        orderDetail.setPrice(item.getPrice());
        orderDetail.setSpec(item.getSpec());
        orderDetail.setNum(integer);
        orderDetail.setItemId(item.getId());
        orderDetail.setTitle(item.getName());
        //添加订单详情
        //根据addressId查询user-service服务，获取地址信息
        String s = iOrderDetail.InsertOrderDetail(orderDetail);
        //将user-service的根据id查询地址接口封装为FeignClient
        List<Address> addressByUserId = userClient.findAddressByUserId(2l);
        OrderLogistics orderLogistics = new OrderLogistics();
        //判断是否为默认地址
        //如果是则加入
        for (Address address : addressByUserId) {
            if (address.getIsDefault()){
                orderLogistics.setOrderId(order1.getId());
                orderLogistics.setContact(address.getContact());
                //手机号验证
                if (RegexUtils.checkMobile(address.getMobile())){
                    throw new BaseException("手机号验证失败");
                }
                orderLogistics.setPhone(address.getMobile());
                orderLogistics.setProvince(address.getProvince());
                orderLogistics.setCity(address.getCity());
                orderLogistics.setTown(address.getTown());
                orderLogistics.setStreet(address.getStreet());
                orderLogistics.setCreateTime(new Date(System.currentTimeMillis()));
            }
        }
        //添加订单地址
        //将地址封装为OrderLogistics对象，写入tb_order_logistics表
        String s1 = iOrderLogistics.InsertOrderLogistics(orderLogistics);
        //在item-service提供减库存接口，并编写FeignClien
        //调用item-service的减库存接口
        String s2 = exampleClient.stockMinus(item.getId(), Long.valueOf(order.getNum()));
        return String.valueOf(order1.getId());
    }
}
